package cn.jiahua.test18;

import java.time.Duration;
import java.time.Instant;
import java.util.OptionalLong;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Test {

    /**
     * 计算100000000 累计求和
     * @param args
     */
    public static void main(String[] args) {
            test1();  //2419  ms
        try {
            test2();   //362  结果是：500000000500000000
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        test3();
    }


    public static void test1(){
        long start=System.currentTimeMillis(); //当前时间，毫秒
        double sum=0;
        for (long i=1;i<=10_0000_0000;i++){
                sum+=i;
        }
        long end=System.currentTimeMillis(); //当前时间，毫秒
        System.out.println(end-start+"  结果是："+sum);
    }

    public static void test2() throws ExecutionException, InterruptedException {
        long start=System.currentTimeMillis(); //当前时间，毫秒


        ForkJoinPool forkJoinPool =new ForkJoinPool();

        JoinpoinDemo joinpoinDemo =new JoinpoinDemo(1L,10_0000_0000L);

        ForkJoinTask<Long> result=  forkJoinPool.submit(joinpoinDemo);
        Long sum=result.get();

        long end=System.currentTimeMillis(); //当前时间，毫秒
        System.out.println(end-start+"  结果是："+sum);
    }

    public static void test3(){
        long start=System.currentTimeMillis(); //当前时间，毫秒
        //使用StreamAPI
        OptionalLong result = LongStream.rangeClosed(0L, 10_0000_0000L)
                    .parallel()
                    .reduce(Long::sum);

        System.out.println(result.getAsLong());
        long end=System.currentTimeMillis(); //当前时间，毫秒
        System.out.println( end-start+"  --10亿求和耗费的时间为: " );

    }


}
